<?php

namespace Common\Model;

use Think\Model;

class UserIntegralLogModel extends Model {

    /**
     * 添加经验值
     * @param $user_id int 用户ID
     * @param $integral_type_id int 经验值来源ID    //在 qy_integral_type 查看ID所属 1-培训视频 2-公开课 3-随堂练习 4-随堂进阶
     * @param $relat_id int 相关ID
     */
    public function addUserIntegral($user_id, $integral_type_id,$relat_id =0) { 
        $IntegralTypeInfo = M('integral_type')->where(array('integral_type_id'=>$integral_type_id))->find();
        if($IntegralTypeInfo['max_integral_limit']){
            //有上限-按每天上限统计
            $arrWhere['user_id'] = $user_id;
            $arrWhere['integral_type_id'] = $integral_type_id;
            $arrWhere['create_time'] = array('between', array(date('Y-m-d,00:00:00'), date('Y-m-d,23:59:59')));
            $integral_sum = $this->where($arrWhere)->getField('sum(integral) as integral_sum');
            if(intval($integral_sum) >= $IntegralTypeInfo['max_integral_limit']){
                return FALSE;
            }
        }else{
            //无上限-按相关ID统计
            if(empty($relat_id)) return FALSE;
            $arrWhere['user_id'] = $user_id;
            $arrWhere['integral_type_id'] = $integral_type_id;
            $arrWhere['relat_id'] = $relat_id;
            $integral_res = $this->where($arrWhere)->count();
            if($integral_res){
                return FALSE;
            }
            
        }
        
        //添加经验值记录
        D()->startTrans();
        $data['user_id']            = $user_id;
        $data['integral_type_id']   = $integral_type_id;
        $data['integral']           = $IntegralTypeInfo['single_integral'];
        $data['relat_id']           = $relat_id;
        $data['create_time']        = date('Y-m-d H:i:s');
        $integral_id = $this->add($data);
        
        //计入总经验分值
        $integralTypeInfo = M('integral_type')->where(array('integral_type_id'=>$integral_type_id))->find();

        $UserIntegral = M('user_integral');
        $count = $UserIntegral->where(array('user_id'=>$user_id))->count();
        if($count){
            $IntegralRes = $UserIntegral->where(array('user_id'=>$user_id))->setInc('total_integral',$integralTypeInfo['single_integral']);
        }else{
            $data['user_id'] = $user_id;
            $data['total_integral'] = $integralTypeInfo['single_integral'];
            $data['create_time'] = date('Y-m-d H:i:s');
            $IntegralRes = $UserIntegral->add($data);
        }
        
        if(!empty($integral_id) && !empty($IntegralRes)){
            D()->commit();
        }else{
            D()->rollback();
        }
    }
    

}
